package com.dragon.modules.yuegou.service.impl.lot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.lot.ActivityDetailEntity;
import com.dragon.modules.yuegou.entity.lot.ActivityEntity;
import com.dragon.modules.yuegou.entity.lot.ActivityJoinEntity;
import com.dragon.modules.yuegou.entity.lot.MemberTicketEntity;
import com.dragon.modules.yuegou.entity.merchant.MerchantEntity;
import com.dragon.modules.yuegou.entity.order.GoodsEntity;
import com.dragon.modules.yuegou.entity.product.SkuEntity;
import com.dragon.modules.yuegou.entity.product.SpuEntity;
import com.dragon.modules.yuegou.enums.code.ActivityCode;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.lot.ActivityProcessStatus;
import com.dragon.modules.yuegou.enums.lot.ActivityPublishStatus;
import com.dragon.modules.yuegou.enums.lot.ParticipationStatus;
import com.dragon.modules.yuegou.enums.order.OrderType;
import com.dragon.modules.yuegou.enums.product.SpuPublishStatus;
import com.dragon.modules.yuegou.enums.product.StockChangeType;
import com.dragon.modules.yuegou.mapper.lot.ActivityMapper;
import com.dragon.modules.yuegou.model.lot.Activity;
import com.dragon.modules.yuegou.model.lot.ActivityDetail;
import com.dragon.modules.yuegou.model.lot.ActivityJoin;
import com.dragon.modules.yuegou.model.lot.MemberTicket;
import com.dragon.modules.yuegou.model.lot.Prize;
import com.dragon.modules.yuegou.model.merchant.Merchant;
import com.dragon.modules.yuegou.model.order.Order;
import com.dragon.modules.yuegou.model.product.Spu;
import com.dragon.modules.yuegou.query.lot.AcrivityJoinListQuery;
import com.dragon.modules.yuegou.query.lot.ActivityJoinQuery;
import com.dragon.modules.yuegou.query.lot.ActivityListQuery;
import com.dragon.modules.yuegou.query.lot.ActivityQuery;
import com.dragon.modules.yuegou.query.lot.MemberTicketQuery;
import com.dragon.modules.yuegou.query.order.GoodsQuery;
import com.dragon.modules.yuegou.query.product.SpuQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.lot.ActivityDetailService;
import com.dragon.modules.yuegou.service.lot.ActivityJoinService;
import com.dragon.modules.yuegou.service.lot.ActivityService;
import com.dragon.modules.yuegou.service.lot.MemberTicketService;
import com.dragon.modules.yuegou.service.merchant.MerchantService;
import com.dragon.modules.yuegou.service.order.GoodsService;
import com.dragon.modules.yuegou.service.order.OrderService;
import com.dragon.modules.yuegou.service.product.SkuService;
import com.dragon.modules.yuegou.service.product.SpuMerchantRefService;
import com.dragon.modules.yuegou.service.product.SpuService;
import com.dragon.modules.yuegou.service.product.StockService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import com.dragon.modules.yuegou.web.Check;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 抽奖活动表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-10-24 10:22:54
 * @version 2.0
 */
@Slf4j
@Service("activityService")
public class ActivityServiceImpl
		extends ServiceImpl<ActivityMapper, ActivityEntity>
		implements ActivityService {

	@Autowired
	private ActivityDetailService activityDetailService;
	
	@Autowired
	private SkuService skuService;
	
	@Autowired
	private SpuService spuService;

	@Autowired
	private SpuMerchantRefService spuMerchantRefService;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private ActivityJoinService activityJoinService;
	
	@Autowired
	private MemberTicketService memberTicketService;
	
	@Autowired
	private ActivityMapper activityMapper;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private StockService stockService;
	
	@Autowired
	private DistrictService districtService;
	
	@Autowired
	private GoodsService goodsService;

	private Random random = new Random();

	
	@Override
	public IPage<Activity> searchList(PageRequest page, ActivityListQuery query) {
		IPage<Activity> activityIPage = activityMapper.search(PageToResultUtils.resultToPage(page), query);
		activityIPage.getRecords().stream().forEach(activity -> {
			if (StringUtils.isEmpty(activity.getMerchantName())){
				SkuEntity sku = skuService.getById(activity.getSkuId());
				List<Merchant> merchantList = spuMerchantRefService.getMerchantListBySpuId(sku.getSpuId());
				String merchantNames = merchantList.stream().map(Merchant::getMerchantName).distinct().collect(Collectors.joining(","));
				activity.setMerchantName(merchantNames);
			}
		});
		return activityIPage;
	}

	@Override
	public void upperActivity(String id) {
		Check.notEmpty(id, "抽奖ID不能为空");
		
		ActivityEntity activity = getById(id);
		activity.setPublishStatus(ActivityPublishStatus.UPPER);
		baseMapper.updateById(activity);
	}

	@Override
	public void lowerActivity(String id) {
		Check.notEmpty(id, "抽奖ID不能为空");
		ActivityEntity activity = getById(id);
		activity.setPublishStatus(ActivityPublishStatus.LOWER);
		baseMapper.updateById(activity);
	}

	
	@Override
	public IPage<Activity> search(PageRequest page, String busdId) {
		Check.notEmpty(busdId, BusinessCode.BUSDID_NOTNULL.getMessage());
		
		ActivityQuery query = new ActivityQuery();
		query.setBusdId(busdId);
		query.setPublishStatus(ActivityPublishStatus.UPPER);

		QueryWrapper<ActivityEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByAsc(ActivityEntity.COL_PROCESS_STATUS);
		wrapper.orderByAsc(ActivityEntity.COL_DRAW_BEGIN_TIME);
		IPage<Activity> iPage = page(PageToResultUtils.resultToPage(page), wrapper);
		
		saveMemberNum(iPage);
		
		return iPage;
	}

	@Override
	public IPage<Activity> pastSearch(PageRequest page, String busdId) {
		Check.notEmpty(busdId,BusinessCode.BUSDID_NOTNULL.getMessage());
		
		ActivityQuery query = new ActivityQuery();
		query.setBusdId(busdId);
		query.drawEndTime().lt(LocalDateTime.now());
		query.setPublishStatus(ActivityPublishStatus.UPPER);
		QueryWrapper<ActivityEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByDesc(ActivityEntity.COL_DRAW_BEGIN_TIME);
		IPage<Activity> iPage =  page(PageToResultUtils.resultToPage(page), wrapper);
		
		saveMemberNum(iPage);
		
		return iPage;
	}
	
	private void saveMemberNum(IPage<Activity> iPage) {
		iPage.getRecords().forEach(activity -> {
			ActivityDetailEntity activityDetail = activityDetailService.getById(activity.getId());
			activity.setMemberNum(activityDetail.getJoinMemberNum());
		});
	}

	@Override
	public Activity getActivity(String id, String memberId) {
		//查询活动信息
		ActivityEntity entity = getById(id);
		
		if (entity == null) {
			throw new DragonException(ActivityCode.ACTIVITY_NOT_EXIST);
		}
		Activity activity= new Activity(entity);
		//获取奖品数量
		ActivityDetailEntity activityDetail = activityDetailService.getById(activity.getId());
		activity.setMemberNum(activityDetail.getJoinMemberNum());
		
		//查询会员抽奖码
		List<MemberTicket> memberTickets = ticketList(memberId,activity.getId());
		activity.setMemberTickets(memberTickets);
		
		//查询活动中奖码
		List<MemberTicket> winningTickets = winningTicketList(activity.getId());
		activity.setWinningMemberTickets(winningTickets);
		
		//获取活动奖品信息
		Spu spu = getSpu(activity.getSkuId());
		activity.setSpu(spu);
		if (StringUtils.isEmpty(activity.getMerchantId())){
			List<Merchant> merchantList = spuMerchantRefService.getMerchantListBySpuId(spu.getId());
			activity.setMerchantList(merchantList);
			activity.setMerchant(merchantList.get(0));
			String merchantNames = merchantList.stream().map(Merchant::getMerchantName).distinct().collect(Collectors.joining(","));
			activity.setMerchantNames(merchantNames);
		}else {
			//获取活动商户信息
			Merchant merchant = getMerchant(activity.getMerchantId());
			activity.setMerchant(merchant);
		}
		activity.setSpuId(spu.getId());
		
		//获取更多活动
		List<Activity> activities = activitieList(activity.getBusdId(),activity.getId());
		activity.setActivitys(activities);
		
		//获取参与活动的用户列表
		List<ActivityJoin> activityJoins = joinList(activity.getId());
		activity.setActivityJoins(activityJoins);
		
		//获取会员参与活动信息
		ActivityJoinQuery query = new ActivityJoinQuery();
		query.setMemberId(memberId);
		query.setActivityId(activity.getId());
		ActivityJoinEntity activityJoin = activityJoinService.getOne(query.toQueryWrapper());
		
		//判断活动状态
		if (activity.getProcessStatus().equals(ActivityProcessStatus.ABOUT_START)) {
			activity.setParticipationStatus(ParticipationStatus.ABOUT_START);
		}else if (activity.getProcessStatus().equals(ActivityProcessStatus.PROCESSIONG)) {
			this.activityProcessiong(activity,activityJoin);
		}else if (activity.getProcessStatus().equals(ActivityProcessStatus.OVER)) {
			//判断会员是否参与该活动
			this.activityOver(activity,activityJoin);
		}
		
		return activity;
	}
	private void activityProcessiong(Activity activity,ActivityJoinEntity activityJoin){
		if (!activity.getIsDraw()) {
			this.activityProcessiongNotDraw(activity,activityJoin);
		}else {
			this.activityProcessiongDraw(activity,activityJoin);
		}
	}
	private void activityProcessiongNotDraw(Activity activity,ActivityJoinEntity activityJoin){
		//判断会员是否参与该活动
		if (activityJoin == null) {
			activity.setParticipationStatus(ParticipationStatus.PARTICIPATE);
		}else {
			if (LocalDateTime.now().isBefore(activity.getDrawBeginTime()) && LocalDateTime.now().isAfter(activity.getJoinEndTime())) {
				activity.setCurrentTime(System.currentTimeMillis());
				activity.setParticipationStatus(ParticipationStatus.SOON_LOTTERY);
			}else if (LocalDateTime.now().isAfter(activity.getJoinBeginTime()) && LocalDateTime.now().isBefore(activity.getJoinEndTime())) {
				activity.setParticipationStatus(ParticipationStatus.ALREADY_INVOLVED);
			}
			activity.setActivityJoin(new ActivityJoin(activityJoin));

		}
	}

	private void activityProcessiongDraw(Activity activity,ActivityJoinEntity activityJoin){
		//判断会员是否参与该活动
		if (activityJoin == null) {
			activity.setParticipationStatus(ParticipationStatus.OVER);
		}else {
			if (activityJoin.getIsPrize()) {
				activity.setParticipationStatus(ParticipationStatus.HAS_WON);
			}else {
				activity.setParticipationStatus(ParticipationStatus.NOT_WON);
			}
		}
	}

	private void activityOver(Activity activity,ActivityJoinEntity activityJoin){
		if (activityJoin == null) {
			activity.setParticipationStatus(ParticipationStatus.OVER);
		}else {
			if (activityJoin.getIsPrize()) {
				activity.setParticipationStatus(ParticipationStatus.HAS_WON);
			}else {
				activity.setParticipationStatus(ParticipationStatus.NOT_WON);
			}
		}
	}

	
	private Spu getSpu(String skuId) {
		//获取sku
		SkuEntity sku = skuService.getById(skuId);
		//获取spu
		SpuEntity spu = spuService.getById(sku.getSpuId());
		return new Spu(spu);
	}
	
	private Merchant getMerchant(String merchantId) {
		return new Merchant(merchantService.getById(merchantId));
	}
	
	private List<ActivityJoin> joinList(String activityId){
		IPage<ActivityJoinEntity> page = new Page<>(1,7,false);

		//获取七条会员参与信息
		ActivityJoinQuery query = new ActivityJoinQuery();
		query.setActivityId(activityId);
		QueryWrapper<ActivityJoinEntity> wrapper =query.toQueryWrapper();
		wrapper.orderByDesc(ActivityJoinEntity.COL_CREATED_TIME);
		IPage<ActivityJoinEntity> iPage = activityJoinService.page(page, wrapper);
		
		return iPage.getRecords().stream().map(ActivityJoin::new).collect(Collectors.toList());
	}
	
	private List<MemberTicket> ticketList(String memberId,String activityId){
		MemberTicketQuery query = new MemberTicketQuery();
		query.setMemberId(memberId);
		query.setActivityId(activityId);
		QueryWrapper<MemberTicketEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByDesc(MemberTicketEntity.COL_CREATED_TIME);
		return memberTicketService.list(wrapper).stream().map(MemberTicket::new).collect(Collectors.toList());
	}
	
	private List<MemberTicket> winningTicketList(String activityId){
		MemberTicketQuery query = new MemberTicketQuery();
		query.setActivityId(activityId);
		query.setIsPrize(true);
		QueryWrapper<MemberTicketEntity> wrapper = query.toQueryWrapper();
		return memberTicketService.list(wrapper).stream().map(MemberTicket::new).collect(Collectors.toList());
	}
	
	private List<Activity> activitieList(String busdId,String activityId){
		//查询该商圈内未结束的其它活动
		ActivityQuery query = new ActivityQuery();
		query.setBusdId(busdId);
		List<String> vals = new ArrayList<>();
		vals.add(activityId);
		query.id().notIn(vals);
		query.setIsDraw(false);
		query.processStatus().eq(ActivityProcessStatus.PROCESSIONG);
		query.setPublishStatus(ActivityPublishStatus.UPPER);
		QueryWrapper<ActivityEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByAsc(ActivityEntity.COL_DRAW_BEGIN_TIME);
		return list(wrapper).stream().map(Activity::new).collect(Collectors.toList());
	}
	
	@Transactional
	@Override
	public void createActivity(Activity activity) {
		Check.notEmpty(activity.getImage(),"活动图片不能为空！");
		Check.notEmpty(activity.getName(),"活动名称不能为空！");
		Check.notNull(activity.getUserJoinMaxNum(), "抽奖号码上限不能为空！");
		Check.positive(activity.getUserJoinMaxNum(), "抽奖号码上限必须为正整数！");
		Check.digits(activity.getUserJoinMaxNum(), 10, 0, "抽奖号码上限必须为正整数！");
		Check.notNull(activity.getJoinBeginTime(), "报名时间不能为空！");
		Check.notNull(activity.getJoinEndTime(), "报名时间不能为空！");
		Check.notNull(activity.getDrawBeginTime(), "开奖时间不能为空！");
		Check.notNull(activity.getAwardNum(), "奖品数量不能为空！");
		Check.positive(activity.getAwardNum(), "奖品数量必须为正整数！");
		Check.digits(activity.getAwardNum(), 10, 0, "奖品数量必须为正整数！");
		//判断抽奖日期是大于报名时间
		if(activity.getDrawBeginTime().isBefore(activity.getJoinEndTime())) {
			throw new DragonException(ActivityCode.LOTTERY_TIME_IS_NOT_CORRECT);
		}
		
		//获取产品信息
		Prize prize = this.getPrizeInfo(activity.getSpuId());
		//判断抽奖日期是否大于奖品可核销时间
		if(activity.getDrawBeginTime().isAfter(prize.getEndTime())) {
			throw new DragonException(ActivityCode.LOTTERY_TIME_IS_NOT_CORRECT);
		}
		//判断奖品数量是否超过库存
		if(activity.getAwardNum() > prize.getStock()) {
			throw new DragonException(ActivityCode.AWARD_NUM_IS_EXCEEDING_STANDARD);
		}
		activity.setMerchantId(prize.getMerchantId());
		activity.setSkuId(prize.getId());
		activity.setSkuName(prize.getTitle());
		activity.setPrice(prize.getPrice());
		activity.setIsDraw(false);
		//如果创建的当前时间在活动费范围内这直接修改进行状态为进行中，状态为上架
		if(LocalDateTime.now().isAfter(activity.getJoinBeginTime()) &&  LocalDateTime.now().isBefore(activity.getJoinEndTime())) {
			activity.setProcessStatus(ActivityProcessStatus.PROCESSIONG);
		} else {
			activity.setProcessStatus(ActivityProcessStatus.ABOUT_START);
		}
		//抽奖结束时间为开奖日期当天的的23:59:59
		activity.setDrawEndTime(LocalDateTime.of(activity.getDrawBeginTime().toLocalDate(), LocalTime.MAX).minusSeconds(1));
		save(activity);
		//创建抽奖活动参与信息
		ActivityDetailEntity activityDetail = new ActivityDetailEntity();
		activityDetail.setId(activity.getId());
		activityDetailService.save(activityDetail);
		
		//减少奖品库存和销量
		stockService.changeStock(prize.getId(), -activity.getAwardNum(), StockChangeType.EDIT);
	}

	@Override
	public List<Spu> getPrizeList(SpuQuery query) {
		//只查询上架商品
		query.setPublishStatus(SpuPublishStatus.UPPER);
		query.beginTime().le(LocalDateTime.now());
		query.endTime().ge(LocalDateTime.now());

		QueryWrapper<SpuEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByAsc(SpuEntity.COL_TITLE);
		return spuService.list(wrapper).stream().map(Spu::new).collect(Collectors.toList());
	}

	@Override
	public Prize getPrizeInfo(String spuId) {
		if (StringUtils.isEmpty(spuId)) {
			Check.notNull(spuId, "奖品ID不能为空");
		}
		Prize prize = activityMapper.getPrizeInfo(spuId);

		List<Merchant> merchantList = merchantService.listBySpuId(spuId);
		if (CollectionUtils.isNotEmpty(merchantList)){
			String merchantName = merchantList.stream().map(Merchant::getMerchantName).collect(Collectors.joining(","));
			prize.setMerchantName(merchantName);
		}
		return prize;
	}
	public void processStatus() {
		// 处理过期状态
		activityMapper.processStatus(ActivityProcessStatus.OVER.getCode().toString());
		// 处理即将开始状态
		activityMapper.processStatus(ActivityProcessStatus.PROCESSIONG.getCode().toString());
	}

	@Override
	public void revealed() {
		activityMapper.getRevealList().forEach(activity -> {
			try {
				processActDraw(activity);
			} catch (Exception e) {
				log.error("{}开奖执行错误",activity.getId(),e);
			}
			
		});
	}

	/**
	 * 处理单个活动的开奖
	 * */
	@Transactional
	public void processActDraw(Activity activity) {
		List<MemberTicket> tickets = runLottery(activity);
		if (CollectionUtils.isEmpty(tickets)) {
			return;
		}
		//给中奖会员创建已支付订单
		tickets.forEach(ticket -> placeOrder(activity,ticket.getMemberId()));
		
		//修改中奖奖券状态
		tickets.forEach(ticket -> ticket.setIsPrize(true));

		memberTicketService.updateBatchById(tickets.stream().map(MemberTicketEntity::new).collect(Collectors.toList()));
		//修改会员参与中奖状态
		List<ActivityJoinEntity> joins = new ArrayList<>();
		tickets.forEach(ticket -> {
			ActivityJoinEntity activityJoin = activityJoinService.getById(ticket.getJoinId());
			if (activityJoin != null) {
				activityJoin.setIsPrize(true);
				joins.add(activityJoin);
			}
		});
		activityJoinService.updateBatchById(joins);
		//修改活动状态为已结束，开奖状态为已开奖
		activity.setIsDraw(true);
		baseMapper.updateById(activity);
		
		// 推送开奖消息
		try {
			pushRunLotteryMsg(activity);
		} catch (Exception e) {
			log.error("开奖发送服务通知出现错误=====>{},{}", e.getMessage(), e);
		}
	}
	
	/**
	 * 事件触发
	 * */
	private void pushRunLotteryMsg(Activity activity) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		//获取AppId
		String appId = districtService.getAppId(activity.getBusdId());
		
		//开奖时间
		String drawBeginTime = df.format(activity.getDrawBeginTime());
		
		//获取商品有效期
		SkuEntity sku = skuService.getById(activity.getSkuId());
		SpuEntity spu = spuService.getById(sku.getSpuId());
		//有效时间
		String writeTime = df.format(spu.getEndTime());
		
		//查询参与会员列表
		ActivityJoinQuery joinQuery = new ActivityJoinQuery();
		joinQuery.setActivityId(activity.getId());
		List<ActivityJoinEntity> joinList = activityJoinService.list(joinQuery.toQueryWrapper());
		
		joinList.stream().forEach(activityJoin -> {
			if (activityJoin.getIsPrize()) {
				//查询单品Id
				GoodsQuery query = new GoodsQuery();
				query.setOrderNo(activityJoin.getOrderNo());
				GoodsEntity goods = goodsService.getOne(query.toQueryWrapper());
				//中奖触发
//				ActivityLotWonEvent event = new ActivityLotWonEvent(goods.getId(),activityJoin.getMemberId(), activity.getSkuName(), drawBeginTime, writeTime,
//						"已中奖，请尽快领奖");
//				event.setAppid(appId);
//				event.setAppversion("2.0");
//				eventPublisher.publish(event);
			}else {
				//未中奖触发
//				ActivityLotNotWonEvent event = new ActivityLotNotWonEvent(activityJoin.getMemberId(), activity.getSkuName(), drawBeginTime, writeTime,
//						"很遗憾，未中奖，看看其他活动吧。");
//				event.setAppid(appId);
//				event.setAppversion("2.0");
//				eventPublisher.publish(event);
			}
		});
	
	}

	/**
	 * 创建订单
	 * */
	@Transactional
	public void placeOrder(Activity activity, String memberId) {
		//创建订单
		Order order = orderService.createNullOrder(activity.getSkuId(), memberId, activity.getBusdId(), OrderType.LOTTERY, true,1);
		
		//查询中奖会员
		ActivityJoinQuery query = new ActivityJoinQuery();
		query.setMemberId(memberId);
		query.setActivityId(activity.getId());
		ActivityJoinEntity join = activityJoinService.getOne(query.toQueryWrapper());
		//插入中奖订单号
		join.setOrderNo(order.getId());
		activityJoinService.updateById(join);
	}
	
	/**
	 * 中奖劵码
	 * */
	private List<MemberTicket> runLottery(Activity activity){
		List<MemberTicketEntity> lucks = new ArrayList<>();
		
		//获取活动下所有奖劵
		MemberTicketQuery memberTicketQuery = new MemberTicketQuery();
		memberTicketQuery.setActivityId(activity.getId());
		List<MemberTicketEntity> tickets = memberTicketService.list(memberTicketQuery.toQueryWrapper());
		
		while (lucks.size() < activity.getAwardNum() && tickets.size() > 0) {
			MemberTicketEntity memberTicket = tickets.get(0);
			if (tickets.size() > activity.getAwardNum()) {
				memberTicket = tickets.get(getRandom(tickets.size()));
			}
			lucks.add(memberTicket);
			List<MemberTicketEntity> copyList = new ArrayList<>();
			for (MemberTicketEntity ticket : tickets) {
				if (!ticket.getMemberId().equals(memberTicket.getMemberId())) {
					copyList.add(ticket);
				}
			}
			tickets = copyList;
		}
		
		return lucks.stream().map(MemberTicket::new).collect(Collectors.toList());
	}
	
	private int getRandom(int max) {
		return random.nextInt(max);
	}

	@Override
	public ActivityDetail getActivityInfo(PageRequest page, AcrivityJoinListQuery query) {
		//获取参与活动信息
		ActivityDetailEntity entity = activityDetailService.getById(query.getActivityId());

		ActivityDetail activityDetail = new ActivityDetail(entity);

		//获取活动中奖的券
		String tickets = activityMapper.getPriceCodes(query.getActivityId(), 1);
		activityDetail.setPriceCodes(tickets);
		//获取参与会员的信息
		IPage<ActivityJoin> activityJoins = activityMapper.getActivityJoinInfo(PageToResultUtils.resultToPage(page), query);
		if(activityJoins.getRecords().size() > 0) {
			List<String> memberIds = new ArrayList<>();
			for(ActivityJoin join : activityJoins.getRecords()) {
				memberIds.add(join.getMemberId());
			}
			MemberTicketQuery memberTicketQuery = new MemberTicketQuery();
			memberTicketQuery.memberId().in(memberIds);
			//添加查询条件当前活动
			memberTicketQuery.activityId().eq(query.getActivityId());
			List<MemberTicketEntity> memberTickets = memberTicketService.list(memberTicketQuery.toQueryWrapper());
			Map<String, List<MemberTicketEntity>> memberTicketMap = memberTickets.stream().collect(Collectors.groupingBy(MemberTicketEntity::getMemberId));
			for(ActivityJoin join : activityJoins.getRecords()) {
				List<MemberTicketEntity> memberTicket = memberTicketMap.get(join.getMemberId());
				if (CollectionUtils.isNotEmpty(memberTicket)){
					join.setMemberList(memberTicket.stream().map(MemberTicket::new).collect(Collectors.toList()));
				}
			}
		}
		activityDetail.setJoinList(activityJoins);
		return activityDetail;
	}

	@Override
	public Activity getActivityDetails(String id) {
		Check.notNull(id, "活动ID不能为空！");
		ActivityEntity entity = getById(id);

		Activity activity= new Activity(entity);
		SkuEntity sku = skuService.getById(activity.getSkuId());
		Prize prize = this.getPrizeInfo(sku.getSpuId());
		activity.setPrize(prize);

		if (sku != null && !StringUtils.isEmpty(sku.getMerchantId())) {
			//查询可核销商户信息
			MerchantEntity merchant = merchantService.getById(sku.getMerchantId());
			activity.setMerchantName(merchant.getMerchantName());
		}else {
			List<Merchant> merchantList = merchantService.listBySpuId(sku.getSpuId());
			if (CollectionUtils.isNotEmpty(merchantList)){
				String merchantName = merchantList.stream().map(Merchant::getMerchantName).collect(Collectors.joining(","));
				activity.setMerchantName(merchantName);
			}
		}
		return activity;
	}
}